package com.gxyk.view;

import com.example.jiemian.R;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.view.ViewHelper;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.ScrollView;
import android.widget.TextView;

public class PullLayout1 extends ScrollView {

	private View rl_top;	
	private ObjectAnimator oa;
	private float lastY = -1;
	private float detalY = -1;
	private int range;	
	private boolean isActionCancel;

	public PullLayout1(Context context) {
		super(context);
	}

	public PullLayout1(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PullLayout1(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();

		rl_top = findViewById(R.id.rl_top);		
		rl_top.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					@SuppressWarnings("deprecation")
					@Override
					public void onGlobalLayout() {
						rl_top.getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);
						range = rl_top.getHeight();					
						rl_top.getLayoutParams().height = range;
					}
				});

	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			isActionCancel = false;
		
			lastY = ev.getY();
			break;
		}
		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (oa != null && oa.isRunning()) {
			ev.setAction(MotionEvent.ACTION_UP);
			isActionCancel = true;
		}
		if (isActionCancel && ev.getAction() != MotionEvent.ACTION_DOWN) {
			return false;
		}	
		switch (ev.getAction()) {
		case MotionEvent.ACTION_MOVE:
			
			if (getScrollY() != 0) {
				detalY = 0;
				lastY = ev.getY();
			} else {
				detalY = ev.getY() - lastY;
				if (detalY > 0) {
					setT((int) -detalY / 5);
					return true;
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			
			reset();
			break;
		}
		return super.onTouchEvent(ev);
	}

	public void setT(int t) {
		if (t < 0) {
			animatePull(t);
		}
	}	
	private void animatePull(int t) {
		rl_top.getLayoutParams().height = range - t;
		rl_top.requestLayout();	
	}

	private void reset() {
		if (oa != null && oa.isRunning()) {
			return;
		}
		oa = ObjectAnimator.ofInt(this, "t", (int) -detalY / 5, 0);
		oa.setDuration(150);
		oa.start();
	}
}
